<template>
  <el-dialog v-model="showDialog" left :append-to-body="true" title="批量新建外壳" class="drag-dialog small-padding-dialog"
    width="60%" destroy-on-close align-center @close="closeDialog">
    <el-tabs v-model="editableTabsValue" type="card" editable class="demo-tabs" @edit="handleTabsEdit">
      <el-tab-pane v-for="item in editableTabs" :key="item.name" :label="item.title" :name="item.name">
        <el-form :model="item.hbForm" label-width="120px" ref="formRef">
          <el-row justify="start">
            <el-col :span="24">
              <el-form-item label="外壳类型" :rules="{ required: true, trigger: ['blur', 'change'], message: '请选择外壳类型' }"
                prop="type">
                <el-select v-model="item.hbForm.type" placeholder="请选择外壳类型" @change="selectType" ref="selectRef">
                  <el-option v-for="it in types" :key="it" :label="it.metaName.replace('元数据', '')" :value="it.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row justify="start">
            <el-col :span="24">
              <el-form-item label="外壳名称" :rules="{ required: true, trigger: ['blur', 'change'], message: '请填写外壳名称' }"
                prop="name">
                <el-input v-model="item.hbForm.name" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row justify="start">
            <el-col :span="24">
              <el-form-item label="目录值" prop="dir">
                <el-input v-model="item.hbForm.dir" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row justify="start">
            <el-col :span="8">
              <label style="width: 120px" class="el-form-item__label">数字化加工文件</label>
            </el-col>
            <el-col :span="8">
              <label style="width: 120px" class="el-form-item__label">元数据信息</label>
            </el-col>
            <el-col :span="8">
              <label class="el-form-item__label">是否必备</label>
            </el-col>
          </el-row>
          <el-row justify="start" v-for="it in item.list" :key="it">
            <el-col :span="8" :offset="8">
              <label style="width: 140px" class="el-form-item__label">{{ it.fieldDesc }}</label>
            </el-col>
            <el-col :span="8">
              <label class="el-form-item__label">
                <el-select v-model="item.hbForm.must[it.name]" style="width: 200px" placeholder="请选择是否必备">
                  <el-option :value="true" label="必备" />
                  <el-option :value="false" label="不必备" />
                </el-select>
              </label>
            </el-col>
          </el-row>
          <el-row justify="start">
            <el-col :span="24">
              <label style="width: 120px" class="el-form-item__label">完整度计算规则</label>
            </el-col>
          </el-row>
          <el-row justify="start">
            <el-col :span="8" :offset="8">
              <label style="width: 120px" class="el-form-item__label">基本信息占比</label>
            </el-col>
            <el-col :span="8">
              <label class="el-form-item__label">
                <el-input v-model="item.hbForm.baseRatio" type="number" placeholder="请输入占比" />
              </label>
            </el-col>
          </el-row>
          <el-row justify="start">
            <el-col :span="8" :offset="8">
              <label style="width: 120px" class="el-form-item__label">数字化加工占比</label>
            </el-col>
            <el-col :span="8">
              <label class="el-form-item__label">
                <el-input v-model="item.hbForm.processRatio" type="number" placeholder="请输入占比" />
              </label>
            </el-col>
          </el-row>
          <el-row justify="start">
            <el-col :span="8" :offset="8">
              <label style="width: 120px" class="el-form-item__label">审核占比</label>
            </el-col>
            <el-col :span="8">
              <label class="el-form-item__label">
                <el-input v-model="item.hbForm.examineRatio" type="number" placeholder="请输入占比" />
              </label>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="closeDialog">关闭</el-button>
        <el-button type="primary" @click="saveForm">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, ref } from 'vue'
import * as houseBookApi from '@/api/house/book'
import * as metaApi from '@/api/meta'

let tabIndex = 1
const editableTabsValue = ref('1')
const editableTabs = ref([
  {
    title: '新建外壳',
    name: '1',
    hbForm: {
      baseRatio: 30,
      processRatio: 30,
      examineRatio: 40,
      must: {}
    },
    list: []
  }
])

const showDialog = ref(false)

const formRef = ref()

const types = ref([])
const type = ref()

const openDialog = () => {
  showDialog.value = true
}

const closeDialog = () => {
  showDialog.value = false
  editableTabs.value = [{
    title: '新建外壳',
    name: '1',
    hbForm: {
      baseRatio: 30,
      processRatio: 30,
      examineRatio: 40,
      must: {}
    },
    list: []
  }]
  editableTabsValue.value = '1'
}

const saveForm = async () => {
  let passedVerification // 是否通过校验
  for (let i = 0; i < formRef.value.length; i++) {
    passedVerification = await formRef.value[i].validate(v => v) // 表单验证
    if (!passedVerification) { // 验证不通过跳出循环 切换到未通过验证的表单
      editableTabsValue.value = editableTabs.value[i].name
      break
    }
    if (editableTabs.value[i].hbForm.type === 42) {
      const hasTrueValue = Object.values(editableTabs.value[i].hbForm.must).some(v => v === true)
      if (!hasTrueValue) {
        ElMessage.warning('请至少选择一个元数据信息必备项')
        passedVerification = false
      }
    }
    const baseRatio = editableTabs.value[i].hbForm.baseRatio
    const processRatio = editableTabs.value[i].hbForm.processRatio
    const examineRatio = editableTabs.value[i].hbForm.examineRatio
    if (baseRatio + processRatio + examineRatio !== 100) {
      ElMessage.warning('请检查完整度计算规则占比之和是否为100')
      passedVerification = false
    }
  }

  if (passedVerification) { // 全部通过校验后发起请求
    const params = editableTabs.value.map(i => i.hbForm)
    await houseBookApi.saveBatch(params)
    showDialog.value = false
    getList()
  }
}

const handleTabsEdit = (targetName, action) => {
  if (action === 'add') {
    const newTabName = `${++tabIndex}`
    editableTabs.value.push({
      title: '新建外壳',
      name: newTabName,
      hbForm: {
        baseRatio: 30,
        processRatio: 30,
        examineRatio: 40,
        must: {}
      },
      list: []
    })
    editableTabsValue.value = newTabName
  } else if (action === 'remove') {
    const tabs = editableTabs.value
    let activeName = editableTabsValue.value
    if (activeName === targetName) {
      tabs.forEach((tab, index) => {
        if (tab.name === targetName) {
          const nextTab = tabs[index + 1] || tabs[index - 1]
          if (nextTab) {
            activeName = nextTab.name
          }
        }
      })
    }
    editableTabsValue.value = activeName
    editableTabs.value = tabs.filter((tab) => tab.name !== targetName)
  }
}

const getList = inject('getList')

const params = reactive({
  pageNo: 1,
  pageSize: 50,
  shelled: true
})

const getType = async () => {
  let res = await metaApi.page(params)
  types.value = res.list
}

const fieldParams = reactive({
  pageNo: 1,
  pageSize: 500,
  fieldDesc: '',
  shelled: true,
  createTime: []
})

const list = ref([])
const selectRef = ref()

const selectType = async (value) => {
  const index = editableTabs.value.findIndex(tabs => tabs.name === editableTabsValue.value)
  types.value.forEach((res) => {
    if (value == res.id) {
      editableTabs.value[index].hbForm.typeName = res.metaName.replace('元数据', '')
    }
  })
  let res = await metaApi.selectField(fieldParams, value)
  editableTabs.value[index].list = res
}

defineExpose({
  openDialog,
})

onMounted(() => {
  getType()
})
</script>
<style>
.file-count {
  width: 120px;
}

.el-row {
  margin-bottom: 20px;
}
</style>
